//
//  BaseListViewController.swift
//  funcode
//
//  Created by Wan Jiading on 2016/11/24.
//  Copyright © 2016年 WanJiading. All rights reserved.
//

import UIKit

class BaseListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

	@IBOutlet weak var tableView: UITableView!
	let cellID = "BaseCell"
	
	let customPop: String = "自定义侧滑返回"
	let customPop1: String = "自定义侧滑返回"
	var dataList: [String]!
	
	var rootVC: UIViewController!
	var vc: UIViewController!
	
    override func viewDidLoad() {
        super.viewDidLoad()

		initData()
    }
	
	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		self.navigationItem.title = "BaseList"
	}
	
	func initData() {
		dataList = [customPop, customPop1]
		
		tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
	}
	
	func dismissSelf() {
		self.dismiss(animated: true, completion: { [unowned self] in
			self.tableView.deselectRow(at: self.tableView.indexPathForSelectedRow!, animated: true)
		})
	}
	
	func pushVC() {
		rootVC.navigationController?.pushViewController(vc, animated: true)
	}
	
	// MARK: - UITableViewDataSource
	
	func numberOfSections(in tableView: UITableView) -> Int {
		return 1
	}
	
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return dataList.count
	}
	
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		
		var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
		if cell == nil {
			cell = UITableViewCell(style: .default, reuseIdentifier: cellID)
		}
		cell!.textLabel?.text = dataList[indexPath.row]
		
		return cell!
	}
	
	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		if rootVC == nil {
			rootVC = UIViewController()
		}
		rootVC.view.backgroundColor = UIColor.white
		rootVC.title = "rootVC"
		rootVC.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(dismissSelf))
		rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Push", style: .done, target: self, action: #selector(pushVC))
		
		var nav: UINavigationController!
		
		let title = dataList[indexPath.row]
		switch title {
			
		case customPop:
			vc = BaseDemo1ViewController()
			nav = UINavigationController(rootViewController: rootVC)
			break
			
		case customPop1:
			vc = BaseDemo1ViewController()
			nav = UINavigationController(rootViewController: rootVC)
			break
			
		default: break
			
		}
		
		nav.pushViewController(vc, animated: true)
		vc.title = title
		vc.view.backgroundColor = UIColor.random
		
		self.present(nav, animated: true, completion: nil)
	}

}
